上次跟大家分享了寫測試的好處與如何撰寫測試之後,大家有自己試著寫寫看嗎?今天要來調整上次所寫的測試程式碼,令它能夠測試我們昨天所撰寫的程式。
先來看一下昨天最終的程式碼,首先是 index.ts 的部份:
// 以上略
export function helloWorld(_options: any): Rule {
  return (_tree: Tree, _context: SchematicContext) => {
    const sourceTemplates = url('./files');
    const sourceParametrizedTemplates = apply(sourceTemplates, [
      template({
        ..._options,
        ...strings
      })
    ]);
    return mergeWith(sourceParametrizedTemplates);
  };
}
接著是範本檔案 hello-__name@dasherize__.component.ts 的部份:
import { Component, Input } from '@angular/core';
@Component({
  selector: 'hello-<%= dasherize(name) %>',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class Hello<%= classify(name) %>Component  {
  @Input() name: string;
}
這次的需求是:
根據範本產出檔案,檔案檔名為
'hello-' + dasherize 過的 name 參數的值 + '.component.ts'
由於需要 dasherize 的關係,所以要跟 index.ts 一樣引入 strings :
import { strings } from '@angular-devkit/core';
接著將 describe 內的測試案例改成:
describe('hello-world', () => {
  it('成功產出檔案,檔名為 "/hello-leo-chen.component.ts"', () => {
    const name = 'LeoChen';
    const runner = new SchematicTestRunner('schematics', collectionPath);
    const tree = runner.runSchematic('hello-world', { name: name }, Tree.empty())
    
    const dasherizeName = strings.dasherize(name);
    const fullFileName = `/hello-${dasherizeName}.component.ts`;
    expect(tree.files).toContain(fullFileName);
  });
});
然後輸入 npm test 驗證看看,應該要是可以通過的:

檔名驗證沒問題之後,那內容要怎麼驗證?!
基本上,由於是直接從範本產出的關係,基本上是不需要特別做驗證,除了某些比較特別的地方,像是 Angular 官方在測試 ng generate component [name] 的產出結果時,因為該 Schematic 會去修改 module.ts 的關係,所以也只特別針對 module.ts 的內容去驗證。
而我們現在也可針對比較需要驗證的地方來撰寫測試,像是檢查使用所輸入的參數有沒有正確的被 dasherize 或是 classify ,是一種比較好寫也比較需要測試的地方。
最後,使用正規表示法來驗證內容的正確性:
describe('hello-world', () => {
  it('成功產出檔案,檔名為 "/hello-leo-chen.component.ts"', () => {
    // 略
    
    const fileContent = tree.readContent(fullFileName);
    expect(fileContent).toMatch(/hello-leo-chen/);
    expect(fileContent).toMatch(/HelloLeoChenComponent/);
  });
});
寫完測試後,記得存檔並輸入
npm test來實際測試看看有沒有任何問題噢!
今天的程式碼在這裡: https://github.com/leochen0818/angular-schematics-30days-challenge/tree/day07
這次是我們第二次寫 Schematics 的測試囉,有沒有覺得其實寫測試非常簡單、用測試來驗證結果也非常方便且快速呢?!
明天筆者要分享的如何初步地在 Angular CLI 上使用自己所撰寫的 Schematic ,敬請期待!